package com.example.demo.mvc.frame;


import com.example.demo.mvc.frame.annotation.GPAutoWired;
import com.example.demo.mvc.frame.annotation.GPController;
import com.example.demo.mvc.frame.annotation.GPRequestMapping;
import com.example.demo.mvc.frame.annotation.GPService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * @author zzf
 * @date 2018/8/10 23:12.
 */
public class GPServletDispather extends HttpServlet{

    private Properties contextConfig = new Properties();

    private List<String> classNames = new ArrayList<>();

    private Map<String, Object> ioc = new HashMap<>();

    private Map<String, Method> handlerMapping = new HashMap<>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //6\调用doDispath
        doDispather(req, resp);
    }

    private void doDispather(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //TODO  路径没有 /
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();

        //绝对路径 -》 相对路径
        url = url.replace(contextPath, "").replaceAll("/+", "/");

        if (!handlerMapping.containsKey(url)) {
            resp.getWriter().write("404 not found");
            return;
        }

        Method method = this.handlerMapping.get(url);

        //执行

        System.out.println(method);
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1\加载配置
        loadConfig();

        //2\扫描包类
        doScanner(contextConfig.getProperty("scanPackage"));

        //3\初始化类，存入ioc容器
        doInstance();

        //4\DI
        doAutowired();

        //5\初始化HandlerMapping
        initHandlerMapping();

        System.out.println("init over!");
    }

    private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();

            if (!clazz.isAnnotationPresent(GPController.class)) {
                continue;
            }

            String baseUrl = "";
            if (clazz.isAnnotationPresent(GPRequestMapping.class)) {

                GPRequestMapping requestMapping = clazz.getAnnotation(GPRequestMapping.class);
                baseUrl = requestMapping.value();
            }

            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(GPRequestMapping.class)) {
                    continue;
                }
                GPRequestMapping requestMapping = method.getAnnotation(GPRequestMapping.class);
                String url = (baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");

                handlerMapping.put(url, method);

                System.out.println("url: " + url + ", method: " + method);
            }


        }

    }

    private void doAutowired() {
        if (ioc.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //属性赋值
            Field[] fields = entry.getValue().getClass().getDeclaredFields();

            for (Field field : fields) {
                if (!field.isAnnotationPresent(GPAutoWired.class)) {
                    continue;
                }
                GPAutoWired autoWired = field.getAnnotation(GPAutoWired.class);

                String beanName = autoWired.value();
                if ("".equals(beanName.trim())) {
                    beanName = field.getType().getName();
                }

                //赋值
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    private void doInstance() {

        if (classNames.isEmpty()) {
            return;
        }
        try {

            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);
                //反射 创造对象
                if (clazz.isAnnotationPresent(GPController.class)) {
                    Object instance = clazz.newInstance();

                    String beanName = lowerFirstCasse(clazz.getSimpleName());
                    //key class 首字母小写
                    ioc.put(beanName, instance);
                } else if (clazz.isAnnotationPresent(GPService.class)) {
                    //service 有自定义，接口等
                    //1、默认的类名首字母小写

                    //2、自定义 beanName，优先使用

                    //3、接口，自动注入 实现类

                    GPService service = clazz.getAnnotation(GPService.class);
                    String beanName = service.value();
                    if ("".equals(beanName)) {
                        beanName = lowerFirstCasse(clazz.getSimpleName());
                    }
                    Object instance = clazz.newInstance();
                    ioc.put(beanName, instance);

                    Class<?>[] interfaces = clazz.getInterfaces();
                    for (Class<?> i : interfaces) {
                        ioc.put(i.getName(), instance);
                    }

                } else {
                    continue;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String lowerFirstCasse(String simpleName) {

        char[] chars = simpleName.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    public static void main(String[] args) {
        System.out.println(GPServletDispather.class.getClassLoader().getResource("/com/example/demo"));
        System.out.println(GPServletDispather.class.getClassLoader().getResource("").getPath());
        System.out.println(GPServletDispather.class.getClassLoader().getResource("com/example/demo"));
    }

    private void doScanner(String scanPackage) {

        URL url = this.getClass().getClassLoader().getResource( scanPackage.replaceAll("\\.", "/"));
        File classPathDir = new File(url.getFile());

        for (File file : classPathDir.listFiles()) {
            if (file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName());
            } else {
                String className = (scanPackage + "." + file.getName()).replace(".class", "");
                classNames.add(className);
            }
        }

    }


    private void loadConfig() {
        //
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("application.properties");
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
